# -*- coding: utf-8 -*-
#   全局域字典
#   任何模块都可以访问，自动处理缺失项
# @Time    ： 2025/7/14  02:21
# @Auther  ： 徐良
# File     :  global_domain.py

from threading import Lock
from typing import Any, Dict, Callable


class DomainDict:
    def __init__(self):
        self._data: Dict[str, Any] = {}
        self._lock = Lock()
        self._data['xuLiang'] = 'my brother'

    def get_or_add(self, key: str, default_factory: Callable[[str], Any] = None) -> Any:
        """
        获取键对应的值，如果不存在则通过default_factory创建并添加

        Args:
            key: 要查找的键
            default_factory: 接收key作为参数的回调函数
        """
        with self._lock:
            if key not in self._data and callable(default_factory):
                self._data[key] = default_factory(key)  # 将key传给回调函数
            return self._data.get(key)  # 返回None如果key不存在且没有default_factory

    def set(self, key: str, value: Any) -> None:
        """设置键值对"""
        with self._lock:
            self._data[key] = value

    def get(self, key: str, default=None) -> Any:
        """获取键对应的值"""
        with self._lock:
            return self._data.get(key, default)

    def __contains__(self, key: str) -> bool:
        """检查键是否存在"""
        with self._lock:
            return key in self._data


# 创建全局实例
domain_dict = DomainDict()
